import "../core/messenger"

window.CnkiSearch = (function () {
  /**
   * 搜索项目的构造函数
   * @param id iframe的id
   * @param url iframe的地址
   * @param token
   * @param userID
   * @param fullHeight 阅读时的高度
   * @param apiurl
   * @constructor
   */
  function CnkiSearch({id, url, token, userID, fullHeight, apiurl, isAddBtn, imgArr, addBtnName, isFullScreenBtn}) {
    this.id = id;
    this.url = url;
    this.qStringObj = {
      token,
      userID,
      fullHeight,
      apiurl,
      isAddBtn,
      imgArr,
      addBtnName,
      isFullScreenBtn
    };
    this.cbs = {};
    this.messenger = null;
    this.msgCnkiSearch = null;
    this._init();
  }

  CnkiSearch.prototype = {
    // 初始化，指定iframe的地址
    _init() {
      this.ifrDom = document.getElementById(this.id);
      this.ifrDom.src = this._setUrl();
      this.ifrDom.style.width = "100%";
      if(!this.ifrDom.style.height) {
        this.ifrDom.style.height = "100%";
      }
      this.ifrDom.frameBorder = 0;
      this._setMsgChannel();
    },
    // 计算url
    _setUrl() {
      let params = "";
      for (let key in this.qStringObj) {
        if(this.qStringObj[key]){
          params += `&${key}=${this.qStringObj[key]}`;
        }
      }
      return this.url + "?" + params.substring(1);
    },
    // 调整阅读屏幕的高度
    _adjustFullHeight(value){
      this.msgCnkiSearch.send(JSON.stringify({
        cmd: "setFullHeight",
        param: value
      }));
    },
    // 设置消息通道
    _setMsgChannel(){
      this.messenger = new Messenger('cnkiParent', 'Editor');
      this.messenger.addTarget(this.ifrDom.contentWindow, "editorParent");
      this.msgCnkiSearch = this.messenger.targets["editorParent"];
      this.messenger.listen(msg => {
        try{
          msg = JSON.parse(msg);
        }catch (e) {
          console.log(e);
          alert(e)
        }
        this.cbs[msg.type] && this.cbs[msg.type].call(null, msg.data);
      })
    },


    // 监听事件
    on(type, fn) {
      switch (type) {
        case "add-to-course":
          this.cbs["addToCourse"] = fn;
          break;
        case "add-ref":
          this.cbs["addRef"] = fn;
          break;
        case "add-stat":
          this.cbs["addStat"] = fn;
          break;
        case "read-full-screen":
          this.cbs["readFullScreen"] = fn;
          break;
        default:
          alert("unassigned event type!");
      }
    },
    // 触发事件
    fire(type, data) {
      switch (type) {
        case "set-fullHeight":
          this._adjustFullHeight(data);
          break;
        default:
          alert("unassigned event type!");
      }
    },
  };

  Object.defineProperty(CnkiSearch.prototype, 'constructor', {
    enumerable: false,
    value: CnkiSearch
  });

  return CnkiSearch;
})();
